import { ipcMain } from 'electron'
import mysql from 'mysql2/promise'

const pool = mysql.createPool({
  host: '10.250.209.12',
  port: 30005,
  user: 'root', // 数据库用户名
  password: 'Tianjun@2020', // 数据库密码
  database: 'rmtj-dev', // 数据库名
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0,
  charset: 'utf8mb4'
})

const genId = () => Date.now().toString() + Math.floor(Math.random() * 10000).toString()

export const setupDictToDbHandlers = () => {
  ipcMain.handle('dict-to-db', async (_event, dictJson: any) => {
    const conn = await pool.getConnection()
    try {
      const insertSql = `
        INSERT INTO dev_dict
          (ID, TENANT_ID, PARENT_ID, DICT_LABEL, DICT_VALUE, CATEGORY, DELETE_FLAG, CREATE_TIME, SORT_CODE)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
      `
      for (const [category, itemsRaw] of Object.entries(dictJson)) {
        const items = itemsRaw as any[]
        const parentId = genId()
        const now = new Date()
        await conn.execute(insertSql, [
          parentId,
          '-1',
          '0',
          category,
          category,
          'BIZ',
          'NOT_DELETE',
          now,
          0
        ])
        const allNumber = items.every((item) => /^\d+$/.test(item.value))
        let sortedItems = items
        if (allNumber) {
          sortedItems = [...items].sort((a, b) => Number(a.value) - Number(b.value))
        }
        let sortCode = 1
        for (const item of sortedItems) {
          await conn.execute(insertSql, [
            genId(),
            '-1',
            parentId,
            item.label,
            item.value,
            'BIZ',
            'NOT_DELETE',
            now,
            (item.sort === '0' ? sortCode : item.sort) || sortCode
          ])
          sortCode++
        }
      }
      return { success: true }
    } catch (err: any) {
      console.error(err)
      return { success: false, error: err.message }
    } finally {
      conn.release()
    }
  })
}
